// axios基础配置
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import router from '@/router'
// 1.实例化-baseURL + timeout
const httpInstance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000,
})

// 2.拦截器-携带token + 错误处理
// axios请求拦截器
httpInstance.interceptors.request.use(
  (config) => {
    // 在Pinia中获取token
    const userStore = useUserStore()
    const token = userStore.userInfo.token
    // 按照后端要求拼接token数据
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (e) => {
    return Promise.reject(e)
  },
)

// axios响应式拦截器
httpInstance.interceptors.response.use(
  (res) => res.data,
  (e) => {
    const userStore = useUserStore()
    // 统一错误提示
    ElMessage({
      type: 'warning',
      message: e.response?.data?.message || '请求失败',
    })
    // 401 token失效处理
    if (e.response?.status === 401) {
      // 清除本地用户数据
      userStore.clearUserInfo()
      // 跳转到登录页
      router.push('/login')
    }
    return Promise.reject(e)
  },
)

export default httpInstance
